using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using ModelContextProtocol.Protocol;
using ProduceBasicData.Api.Application.Command.WarehouseManage;
using ProduceBasicData.Domain.WarehouseManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure;
using ProduceBasicData.Infrastructure.Interface;
using System.Transactions;
using ProduceBasicData.Api.Services;

namespace ProduceBasicData.Api.Application.Handler.WarehouseManage
{
    /// <summary>
    /// 创建入库单处理器
    /// </summary>
    public class CreateStockInOrderHandler : IRequestHandler<CreateStockInOrderCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<StockInOrder> _stockInOrderRepository;
        private readonly IBaseRespository<StockInOrderItem> _stockInOrderItemRepository;
        private readonly IMapper _mapper;
        private readonly MyDBContext _myDBContext;
        private readonly ICodeRuleService codeRuleService;

        public CreateStockInOrderHandler(
            IBaseRespository<StockInOrder> stockInOrderRepository,
            IBaseRespository<StockInOrderItem> stockInOrderItemRepository,
            IMapper mapper,MyDBContext myDBContext,
            ICodeRuleService codeRuleService)
        {
            _stockInOrderRepository = stockInOrderRepository;
            _stockInOrderItemRepository = stockInOrderItemRepository;
            _mapper = mapper;
            _myDBContext = myDBContext;
            this.codeRuleService = codeRuleService;
        }

        /// <summary>
        /// 处理创建入库单请求
        /// </summary>
        /// <param name="request">创建入库单命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<int>> Handle(CreateStockInOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 创建事务
                using var transaction = await _myDBContext.Database.BeginTransactionAsync(cancellationToken);
                try
                {
                    // 映射命令到领域模型
                    var stockInOrder = _mapper.Map<StockInOrder>(request);

                    //编码
                    if (string.IsNullOrEmpty(stockInOrder.OrderNumber))
                    {
                        var code = await codeRuleService.AutoGenerateCodeAsync("ProduceBasicData.Domain.WarehouseManage.StockInOrder");
                        if (!string.IsNullOrEmpty(code))
                        {
                            stockInOrder.OrderNumber = code;
                        }
                        else
                        {
                            stockInOrder.OrderNumber = $"RK{DateTime.Now:yyyyMMddHHmmss}";
                        }
                    }

                    // 保存入库单
                    await _stockInOrderRepository.AddAsync(stockInOrder);

                    // 处理入库单明细
                    if (request.Items != null && request.Items.Any())
                    {
                        foreach (var itemCommand in request.Items)
                        {
                            var item = _mapper.Map<StockInOrderItem>(itemCommand);

                            //编码
                            if (string.IsNullOrEmpty(item.SytemNo))
                            {
                                var code = await codeRuleService.AutoGenerateCodeAsync("ProduceBasicData.Domain.WarehouseManage.StockInOrderItem");
                                if (!string.IsNullOrEmpty(code))
                                {
                                    item.SytemNo = code;
                                }
                                else
                                {
                                    item.SytemNo = $"RKDMX{DateTime.Now:yyyyMMddHHmmss}";
                                }
                            }

                            item.StockInOrderId = stockInOrder.Id;
                            await _stockInOrderItemRepository.AddAsync(item);
                        }
                    }

                    await _myDBContext.SaveChangesAsync(cancellationToken);
                    // 提交事务
                    await transaction.CommitAsync();

                    return new ApiResult<int>
                    {
                        Data = stockInOrder.Id,
                        Code = ApiEnum.Success,
                        Msg = "入库单录入成功"
                    };
                }
                catch (Exception)
                {
                    // 回滚事务
                    await transaction.RollbackAsync();
                    throw;
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"入库单录入失败,{ex.Message}"
                };
            }
        }
    }
}